package com.weizhi.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.weizhi.server.dto.FileDto;
import com.weizhi.server.dto.FileDto;
import com.weizhi.server.entity.File;
import com.weizhi.server.entity.File;
import com.weizhi.server.mapper.CourseMapper;
import com.weizhi.server.mapper.FileMapper;
import com.weizhi.server.service.FileService;
import com.weizhi.server.util.PropertyCopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {
    private final static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Resource
    private FileMapper fileMapper;


    @Override
    public PageInfo list(JSONObject param) {
        PageHelper.startPage(param.getInteger("pageIndex"), param.getInteger("pageSize"));
        List<File> fileList = fileMapper.list();
        PageInfo pageInfo = new PageInfo(fileList);
        List<FileDto> fileDtoList = PropertyCopyUtil.copyList(fileList, FileDto.class);
        pageInfo.setList(fileDtoList);
        return pageInfo;
    }

    @Override
    public void save(FileDto fileDto) {
        File file = new File();
        BeanUtils.copyProperties(fileDto, file);

        if(StringUtil.isEmpty(file.getShareKey())){
            fileMapper.insert(file);
            return;
        }
        File fileDb = fileMapper.selectByShareKey(file.getShareKey());
        if(fileDb == null) {
            fileMapper.insert(file);
        }else{
            fileDb.setShareIndex(file.getShareIndex());
            fileMapper.updateByPrimaryKey(fileDb);
        }
    }

    @Override
    public FileDto check(String shareKey) {
        File fileDb = fileMapper.selectByShareKey(shareKey);
        return PropertyCopyUtil.copy(fileDb, FileDto.class);
    }
}
